import 'dart:convert';

import 'package:gold/base/config.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_gold.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/goods_detail_model.dart';
import 'package:gold/model/review_list_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description:
/// @author tangzhentao
/// @created at 13:38 2024/11/30

class GoodsDetailViewmodel extends Viewmodel {
  /// 积分商品id
  final int goodsId;
  /// 刷新控制器
  final RefreshController controller = RefreshController();

  /// 轮播坐标
  int _carouselIndex = 0;
  int get carouselIndex => _carouselIndex;
  set carouselIndex(int value) {
    if (_carouselIndex != value) {
      _carouselIndex = value;
      notifyListeners();
    }
  }

  /// 全网比价
  final List<PeerModel> _peers = [];
  List<PeerModel> get peers => _peers;
  /// 页码
  int _page = 1;

  /// 商品详情
  GoodsDetailModel? detail;
  /// 评论列表
  final List<ReviewModel> reviewList = [];

  GoodsDetailViewmodel(this.goodsId);

  /// 加载数据
  Future firstLoad() async {
    setLoading();
    _page = 1;
    final result = await Http().request<GoodsDetailModel>(ApiGold.productDetail, data: {'id': goodsId}, showErrorMsg: false);
    final reviewResult = await Http().request<ReviewListModel>(ApiGold.reviewsList, showErrorMsg: false,
        data: {'page': _page, 'filter': {'product_id': goodsId}});
    if (result.success && reviewResult.success) {
      detail = result.data;
      reviewList.clear();
      reviewList.addAll(reviewResult.data?.data?? []);
      if (detail != null) {
        controller.footerMode?.value = _page < (reviewResult.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
        if (detail?.peer?.isNotEmpty == true) {
          final peers = jsonDecode(detail!.peer!) as List<dynamic>;
          _peers.clear();
          for (var e in peers) {
            if (e is Map<String, dynamic>) {
              _peers.add(PeerModel.fromJson(e));
            }
          }
        }
        setSuccess();
      } else {
        setEmpty();
      }
    } else {
      String msg = '';
      if (!result.success) msg = result.msg;
      if (!reviewResult.success) msg = reviewResult.msg;
      setFailed(msg: msg);
    }
  }

  /// 刷新数据
  Future refresh() async {
    _page = 1;
    final result = await Http().request<ReviewListModel>(ApiGold.reviewsList, showErrorMsg: false,
        data: {'page': _page, 'filter': {'product_id': goodsId}});
    if (result.success) {
      controller.refreshCompleted();
      controller.footerMode?.value = _page < (result.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      final data = result.data?.data?? [];
      if (data.isNotEmpty) {
        reviewList.clear();
        reviewList.addAll(data);
        setSuccessChange();
      }
    } else {
      controller.refreshFailed();
    }
  }

  /// 加载更多数据
  Future loadMore() async {
    _page++;
    final result = await Http().request<ReviewListModel>(ApiGold.reviewsList, showErrorMsg: false,
        data: {'page': _page, 'filter': {'product_id': goodsId}});
    if (result.success) {
      controller.loadComplete();
      controller.footerMode?.value = _page < (result.data?.totalPages?? 0) ? LoadStatus.canLoading:LoadStatus.noMore;
      final data = result.data?.data?? [];
      if (data.isNotEmpty) {
        reviewList.addAll(data);
        setSuccessChange();
      } else {
        controller.loadNoData();
      }
    } else {
      controller.loadFailed();
    }
  }

  /// 购买
  Future buy() async {
    XfgNav.pushNamed(Routes.goodsOrder, arguments: detail!);
  }

  @override
  onReload() => firstLoad();

  @override
  onRetry() => firstLoad();

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
